#include "useradminmodel.h"
#include <QColor>
#include <QtSql>

UserAdminModel::UserAdminModel(QObject *parent)
        : UniversalQueryModel(parent)
{
    filterText = "";
    sortOrder = Qt::AscendingOrder;
    //refresh();
}

Qt::ItemFlags UserAdminModel::flags(const QModelIndex &index)
{
    Qt::ItemFlags flags = QSqlQueryModel::flags(index);
    return flags;
}

QVariant UserAdminModel::data(const QModelIndex &index, int role) const
{
    QVariant value = QSqlQueryModel::data(index, role);

    switch (role) {
    case Qt::DisplayRole:
        if (index.column() == 2) {
            int permissions = record(index.row()).value("permission").toInt();

            switch (permissions) {
                case 7 :
                   return tr("Аудитор");
               case 77 :
                    return tr("Оператор");
                case 777 :
                    return tr("Администратор");
            }
        }
        return value;
    case Qt::TextAlignmentRole:
        if (index.column() == 0 || index.column() == 2)
            return int(Qt::AlignVCenter | Qt::AlignCenter);
        else
            return int(Qt::AlignVCenter | Qt::AlignLeft);
    case Qt::BackgroundColorRole:
        if  (index.column() == 0 )
            return qVariantFromValue(QColor(220,240,230));
        else
            return qVariantFromValue(QColor(246,246,250));
    }
    return value;
}


void UserAdminModel::refresh()
{
    sort(sortColumn, sortOrder);
    setHeaderData(0, Qt::Horizontal, tr("#"));
    setHeaderData(1, Qt::Horizontal, tr("Имя пользователя"));
    setHeaderData(2, Qt::Horizontal, tr("Права доступа"));
    setHeaderData(3, Qt::Horizontal, tr("хеш"));
}


void UserAdminModel::sort(int column,Qt::SortOrder order)
{
    saveSelState();
    setQuery(fetchTableData(column, order));
    qDebug() << this->query().lastQuery();
    if (!lastError().isValid()) {
        sortColumn = column;
        sortOrder = order;
        returnSelState();
    } else {
        qDebug() << tr("Sql execute error in UserAdminModel::sort()");
        qDebug() << lastError().text();
    }
    //emit queryUpdated();
}

QString UserAdminModel::fetchTableData(int column, Qt::SortOrder order)
{
    QString query = QString("SELECT id, name, permission, passwd FROM users ");
    if (filterText.trimmed() != ""){
        query += QString(" WHERE name LIKE '%%1%'").arg(filterText.trimmed());
    }
    query += QString(" ORDER BY %1 %2")
             .arg(QString::number(column+1),
                  order == Qt::AscendingOrder ? "ASC" : "DESC");
    qDebug() << query <<" |";
    return query;
}

void UserAdminModel::filtrate(const QString &name)
{
    filterText = name;
    refresh();
}




















